package com.xuecheng.media.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.j256.simplemagic.ContentInfo;
import com.j256.simplemagic.ContentInfoUtil;
import com.xuecheng.base.exception.XCPlusException;
import com.xuecheng.base.model.PageParam;
import com.xuecheng.base.model.PageResult;
import com.xuecheng.base.model.RestResponse;
import com.xuecheng.media.mapper.MediaFilesMapper;
import com.xuecheng.media.model.dto.QueryMediaParamsDto;
import com.xuecheng.media.model.dto.UploadFileParamDto;
import com.xuecheng.media.model.dto.UploadFileResultDto;
import com.xuecheng.media.model.po.MediaFiles;
import com.xuecheng.media.service.MediaFileService;
import io.minio.*;
import io.minio.messages.DeleteObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.*;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @description TODO
 * @author Mr.M
 * @date 2022/9/10 8:58
 * @version 1.0
 */
 @Service
 @Slf4j(topic = "MediaFileServiceImpl")
public class MediaFileServiceImpl implements MediaFileService {

  @Autowired
  MediaFilesMapper mediaFilesMapper;

  //存储普通文件
  @Value("${minio.bucket.files}")
  private String bucket_mediafiles;

  //存储视频
  @Value("${minio.bucket.vediofiles}")
  private String bucket_vedio;

  @Autowired
  private MinioClient minioClient;

 @Override
 public PageResult<MediaFiles> queryMediaFiels(Long companyId, PageParam pageParams, QueryMediaParamsDto queryMediaParamsDto) {

  //构建查询条件对象
  LambdaQueryWrapper<MediaFiles> queryWrapper = new LambdaQueryWrapper<>();
  
  //分页对象
  Page<MediaFiles> page = new Page<>(pageParams.getPageNo(), pageParams.getPageSize());

  // 查询数据内容获得结果
  Page<MediaFiles> pageResult = mediaFilesMapper.selectPage(page, queryWrapper);

  // 获取数据列表
  List<MediaFiles> list = pageResult.getRecords();

  // 获取数据总数
  long total = pageResult.getTotal();

  // 构建结果集
  PageResult<MediaFiles> mediaListResult = new PageResult<>(list, total, pageParams.getPageNo(), pageParams.getPageSize());

  return mediaListResult;

 }

 @Transactional
 @Override
 public UploadFileResultDto uploadFile(Long companyId, UploadFileParamDto uploadFileParamDto, String localFilePath) {


      //先拿到文件名
      String filename = uploadFileParamDto.getFilename();
      //拿扩展名
      String extension = filename.substring(filename.lastIndexOf("."));


     //1.将文件上传到minio
     //1.1拿到文件类型
     String mimeType = getMimeType(extension);

     //上传的目录路径
     String defaultFolderPath = getDefaultFolderPath();

     //文件的MD5值
     String fileMd5 = getFileMd5(new File(localFilePath));

     String objectName = defaultFolderPath + fileMd5 + extension;

     //上传文件的参数信息
     //1.2 文件上传
     boolean result = addMediaTypeToMinio(localFilePath, mimeType, bucket_mediafiles, objectName);

     if (!result){

         XCPlusException.cast("上传文件失败！");
     }

     //2.将文件信息保存到数据库

     //2.1 入库文件信息
     MediaFiles mediaFiles = addMediaFileToDb(companyId, fileMd5, uploadFileParamDto, bucket_mediafiles, objectName);

     if (mediaFiles == null){

         XCPlusException.cast("文件上传后保存文件失败！");
     }

     UploadFileResultDto uploadFileResultDto = new UploadFileResultDto();

     BeanUtils.copyProperties(mediaFiles,uploadFileResultDto);

     return uploadFileResultDto;
 }

    @Override
    public RestResponse<Boolean> checkFile(String fileMd5) {

        // 先查询数据库
        MediaFiles mediaFiles = mediaFilesMapper.selectById(fileMd5);

        if (mediaFiles != null){

            //桶
            String bucket = mediaFiles.getBucket();
            //objectName
            String filePath = mediaFiles.getFilePath();

            //如果数据库存在，再查询Minio
            GetObjectArgs objectArgs = GetObjectArgs.builder()
                    .bucket(bucket)
                    .object(filePath)
                    .build();

            //查询远程服务获取到一个流对象
            try {

                FilterInputStream inputStream = minioClient.getObject(objectArgs);

                //如果从minio查到了
                if (inputStream != null){

                    //minio 中 文件已存在
                    return RestResponse.success(true);
                }


            }catch (Exception e){

                e.printStackTrace();
            }
        }


        //文件不存在
        return RestResponse.success(false);
    }

    @Override
    public RestResponse<Boolean> checkChunk(String fileMd5, int chunkIndex) {

        //得到分块文件目录
        String chunkFileFolderPath = getChunkFileFolderPath(fileMd5);

        //得到分块文件的路径
        GetObjectArgs getObjectArgs = GetObjectArgs.builder()
                .bucket(bucket_vedio)
                .object(chunkFileFolderPath + chunkIndex)
                .build();

        try {

            FilterInputStream inputStream = minioClient.getObject(getObjectArgs);

            //文件已存在
            if (inputStream != null){

                return RestResponse.success(true);
            }

        }catch (Exception e){

            e.printStackTrace();
        }

        return RestResponse.success(false);
    }

    @Override
    public RestResponse uploadChunk(String fileMd5, int chunk, String localChunkFilePath) {

        //分块文件的路径
        String chunkFilePath = getChunkFileFolderPath(fileMd5) + chunk;
        // 扩展名
        String mimeType = getMimeType(null);
        //将分块文件上传到minio
        boolean b = addMediaTypeToMinio(localChunkFilePath, mimeType, bucket_vedio, chunkFilePath);

        if (!b){

            return RestResponse.validfail(false,"分块文件上传失败！");
        }
        return RestResponse.success(true);
    }

    /**
     * 合并分块文件
     * @param companyId 机构ID
     * @param fileMd5 文件的Md5
     * @param chunkTotal 分块总和
     * @param uploadFileParamDto 文件信息
     * @return
     */
    @Override
    public RestResponse mergeChunks(Long companyId, String fileMd5, int chunkTotal, UploadFileParamDto uploadFileParamDto) {

        //分件文件所在目录
        String chunkFileFolderPath = getChunkFileFolderPath(fileMd5);

        log.info("分件文件所在目录:{}",chunkFileFolderPath);

        // 找到所有的分块文件调用minio的sdk进行文件合并

        List<ComposeSource> sourceList = new ArrayList<>();

        //指定分块文件的信息
        for (int i = 0; i < chunkTotal; i++) {

            ComposeSource composeSource = ComposeSource.builder()
                    .bucket(bucket_vedio)
                    .object(chunkFileFolderPath + i)  //分块文件的路径
                    .build();

            sourceList.add(composeSource);
        }

        System.out.println("==========="+sourceList);

        // 先拿到源文件的名称
        String filename = uploadFileParamDto.getFilename();
        // 拿到扩展名
        String extension = filename.substring(filename.lastIndexOf("."));

        //合并后文件的objectName
        String objectName = getFilePathByMd5(fileMd5, extension);

        ComposeObjectArgs composeObjectArgs = ComposeObjectArgs.builder()
                .bucket(bucket_vedio)
                .object(objectName)  // 合并后的文件的objectName
                .sources(sourceList)
                .build();

        //合并分块
       try {

           minioClient.composeObject(composeObjectArgs);

           log.info("分块文件合并成功！");

       }catch (Exception e){

           e.printStackTrace();
           log.error("分块文件合并失败！bucket:{},objectName:{},错误信息:{}",bucket_vedio,objectName,e.getMessage());

           return RestResponse.validfail(false,"文件合并异常！");
       }

        //校验合成后的文件和本地文件是否一致，一致才能上传成功

        //先拿到从minio下载的文件
        File file = downloadFileFromMinio(bucket_vedio, objectName);
       log.info("从minio下载的文件:{}",file);

       try(FileInputStream fileInputStream = new FileInputStream(file)) {

           //计算合并后文件的md5
           String mergeFile_Md5 = DigestUtils.md5Hex(fileInputStream);
           //比较原始文件的md5 和 合并后的md5 是否一致
           if (!mergeFile_Md5.equals(fileMd5)){

               log.error("校验合并文件md5值不一样！原始文件：{},合并后的文件{}",fileMd5,mergeFile_Md5);

               return RestResponse.validfail(false,"校验文件失败！");
           }

           //文件大小
           uploadFileParamDto.setFileSize(file.length());

       }catch (Exception e){

           e.printStackTrace();
       }


        //将文件信息入库
        MediaFiles mediaFileDb = addMediaFileToDb(companyId, fileMd5, uploadFileParamDto, bucket_vedio, objectName);

       log.info("入到库的文件信息:{}",mediaFileDb);
       if (mediaFileDb == null){
            return RestResponse.validfail(false,"文件入库失败！");
       }


        //清理分块文件信息

        cleanChunkFiles(chunkFileFolderPath,chunkTotal);

        return RestResponse.success(true);
    }

    /**
     * 清理分块文件
     * @param chunkFileFolderPath 分块文件路径
     * @param chunkTotal 分块数量
     */
    private void cleanChunkFiles(String chunkFileFolderPath,
                                 int chunkTotal) {


        Iterable<DeleteObject> deleteObjects = Stream.iterate(0, i -> ++i)
                .limit(chunkTotal)
                .map(i -> new DeleteObject(chunkFileFolderPath + i))
                .collect(Collectors.toList());

        RemoveObjectsArgs removeObjectsArgs = RemoveObjectsArgs.builder()
                .bucket(bucket_vedio)
                .objects(deleteObjects)
                .build();

        try {

           minioClient.removeObjects(removeObjectsArgs);

           log.info("分块文件移除成功！");
       }catch (Exception e){

           e.printStackTrace();
       }

    }

    /**
     * TODO 从minio下载文件
     * @param bucket 桶
     * @param objectName 对象名称
     * @return 下载后的文件
     */
    public File downloadFileFromMinio(String bucket,String objectName){

        //临时文件
        File minioFile = null;

        FileOutputStream outputStream = null;

        try {

            InputStream stream = minioClient.getObject(GetObjectArgs.builder()
                    .bucket(bucket)
                    .object(objectName)
                    .build());

            //创建临时文件
            minioFile = File.createTempFile("minio", ".merge");

            outputStream = new FileOutputStream(minioFile);

            //复制
            IOUtils.copy(stream,outputStream);

            return minioFile;

        }catch (Exception e){

            e.printStackTrace();
        }finally {

            if (outputStream != null){

                try {
                    //关闭流
                    outputStream.close();

                }catch (IOException e){

                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    /**
     *  得到合并后的文件地址
     * @param fileMd5 文件的md5值
     * @param fileExt 文件扩展名
     * @return
     */
    public String getFilePathByMd5(String fileMd5,
                                   String fileExt){

        return fileMd5.substring(0,1) + "/" + fileMd5.substring(1,2) + "/" + fileMd5 + "/" + fileMd5 + fileExt;
    }

    /**
     * 得到分块文件目录
     * @param fileMd5
     * @return
     */
    private String getChunkFileFolderPath(String fileMd5) {

       return fileMd5.substring(0,1) + "/" + fileMd5.substring(1,2) + "/" + fileMd5 + "/" + "chunk" + "/";
    }


    /**
  * 根据扩展名获取 MimeType
  * @param extension
  * @return
  */
 private String getMimeType(String extension){

  if (extension == null){
   extension = "";
  }

  ContentInfo extensionMatch = ContentInfoUtil.findExtensionMatch(extension);

  String mimeType = MediaType.APPLICATION_OCTET_STREAM_VALUE;

  if (extensionMatch != null){

   mimeType =  extensionMatch.getMimeType();
  }

  return mimeType;

 }

 /**
  * 将文件上传到minio
  * @param localFilePath 本地文件路径
  * @param mimeType 文件类型
  * @param bucket 桶名称
  * @param objectName 对象名
  * @return
  */
 private boolean addMediaTypeToMinio(String localFilePath,
                                              String mimeType,
                                              String bucket,
                                              String objectName){

  try {

       UploadObjectArgs uploadObjectArgs = UploadObjectArgs.builder()
               .bucket(bucket)
               .filename(localFilePath)
               .object(objectName)
               .contentType(mimeType)
               .build();

       //上传文件
      minioClient.uploadObject(uploadObjectArgs);

      log.info("文件上传到minio成功！");

       return true;

  }catch (Exception e){

      e.printStackTrace();

      log.error("文件上传出错,bucket:{},objectName:{},错误信息:{}",bucket,objectName,e.getMessage());
  }

  return false;
 }

    /**
     * 获取文件默认存储目录路径 年/月/日
     * @return
     */
    private String getDefaultFolderPath(){

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        String folder = sdf.format(new Date()).replace("-","/") + "/";

        return folder;
    }

    /**
     * 拿到文件的MD5值
     * @param file
     * @return
     */
    private String getFileMd5(File file){

        try {

            FileInputStream inputStream = new FileInputStream(file);

            String fileMd5 = DigestUtils.md5Hex(inputStream);

            return fileMd5;

        }catch (Exception e){

            e.printStackTrace();

            return null;
        }

    }


    /**
     * 将文件信息存储到数据库
     * @param companyId 机构ID
     * @param fileMd5   文件MD5值
     * @param uploadFileParamDto    上传文件的信息
     * @param bucket    桶
     * @param objectName    对象名称
     * @return
     */
    private MediaFiles addMediaFileToDb(Long companyId,
                                        String fileMd5,
                                        UploadFileParamDto uploadFileParamDto,
                                        String bucket,
                                        String objectName) {

        MediaFiles mediaFiles = mediaFilesMapper.selectById(fileMd5);

        if (mediaFiles == null) {

            mediaFiles = new MediaFiles();

            BeanUtils.copyProperties(uploadFileParamDto, mediaFiles);
            //文件ID
            mediaFiles.setId(fileMd5);
            //机构ID
            mediaFiles.setCompanyId(companyId);
            //桶
            mediaFiles.setBucket(bucket);
            //file_path
            mediaFiles.setFilePath(objectName);
            //file_id
            mediaFiles.setFileId(fileMd5);
            // url
            mediaFiles.setUrl("/" + bucket + "/" + objectName);
            //上传时间
            mediaFiles.setCreateDate(LocalDateTime.now());
            //状态
            mediaFiles.setStatus("1");
            //审核状态
            mediaFiles.setAuditStatus("002003");

            //插入数据库
            int insert = mediaFilesMapper.insert(mediaFiles);

            if (insert <= 0) {

                log.error("向数据库保存文件失败！bucket:{},objectName:{}", bucket, objectName);

                return null;
            }

            return mediaFiles;
        }

        return mediaFiles;

    }
}
